package com.gxc.event;

import com.gxc.entity.User;
import com.gxc.service.UserService;
import java.time.LocalDate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.event.SmartApplicationListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

/**
 * SmartApplicationListener实现有序监听.
 *
 * @author 宫新程
 * @since 2018/12/6 11:27 AM
 */
@Component
@Slf4j
public class SmartRegisterListener implements SmartApplicationListener {

  /** 该方法返回true&supports SourceType 同样返回true时，才会调用该监听内的onApplicationEvent方法. */
  @Override
  public boolean supportsEventType(Class<? extends ApplicationEvent> aClass) {
    // 只有UserRegisterEvent监听类型才会执行下面逻辑
    return aClass == UserRegisterEvent.class;
  }

  /** 该方法返回true&supports EventType 同样返回true时，才会调用该监听内的onApplicationEvent方法. */
  @Override
  public boolean supportsSourceType(Class<?> sourceType) {
    // 只有在UserService内发布的UserRegisterEvent事件时才会执行下面逻辑
    return sourceType == UserService.class;
  }

  @Override
  @Async
  public void onApplicationEvent(ApplicationEvent applicationEvent) {
    try {
      Thread.sleep(3000); // 静静的沉睡3秒钟
    } catch (Exception e) {
      e.printStackTrace();
    }
    UserRegisterEvent userRegisterEvent = (UserRegisterEvent) applicationEvent;
    User user = userRegisterEvent.getUser();
    log.info(
        "Smart： _____ 用户名：{}，密码：{}，时间：{}", user.getUsername(), user.getPassword(), LocalDate.now());
  }

  /** 同步情况下监听执行的顺序.数值越小证明优先级越高，执行顺序越靠前。 */
  @Override
  public int getOrder() {
    return 0;
  }
}
